import { LogoutOutlined, UnlockOutlined } from "@ant-design/icons";
import { history, useModel } from "@umijs/max";
import type { MenuProps } from "antd";
import { ReactNode, FC } from "react";
import HeaderDropdown from "../HeaderDropdown";
import storage from "../../utils/storage";

export type GlobalHeaderRightProps = {
  children?: ReactNode;
};

export const AvatarName = () => {
  const { initialState } = useModel("@@initialState");
  const { user } = initialState || {};
  return <span className="anticon">{user?.name}</span>;
};

export const AvatarDropdown: FC<GlobalHeaderRightProps> = ({ children }) => {
  const { setInitialState } = useModel("@@initialState");

  const onMenuClick: MenuProps["onClick"] = e => {
    if (e.key !== "logout") {
      history.push("/user/" + e.key);
      return;
    }

    // 退出系统
    console.clear();
    storage.clear();
    setInitialState(() => ({
      loading: false,
      token: "",
      user: {
        id: 0,
        userName: "",
        password: "",
        name: "",
        phone: "",
        email: "",
        status: false,
        roleId: 0,
        remark: "",
        addTime: "",
      },
      accessData: "",
    }));

    history.replace({ pathname: "/user/login" });
    location.reload(); // 不推荐直接刷新页面的做法，会影响到用户体验。
  };

  const menuItems = [
    { key: "changePassword", icon: <UnlockOutlined />, label: "更改密码" },
    { type: "divider" as const },
    { key: "logout", icon: <LogoutOutlined />, label: "退出系统" },
  ];

  return (
    <HeaderDropdown menu={{ selectedKeys: [], onClick: onMenuClick, items: menuItems }}>
      {children}
    </HeaderDropdown>
  );
};
